package com.fileutils;

import android.util.Base64;
import android.util.Log;

import java.nio.charset.StandardCharsets;

/**
 * Created by Administrator on 2019/4/20.
 */

public class ByteUtils {
    /**
     * 将字节 转换为字符串
     *
     * @param src 需要转换的字节数组
     * @return 返回转换完之后的数据
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 数组转成十六进制字符串
     *
     * @param b
     * @return HexString
     */
    public static String toHexString1(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i) {
            buffer.append(toHexString1(b[i]));
        }
        return buffer.toString();
    }

    /**
     * 数组转成十六进制字符串数组
     *
     * @param b
     * @return HexString
     */
    public static String[] toHexStringArr(byte[] b) {
        String[] buffer = new String[b.length];
        for (int i = 0; i < b.length; ++i) {
            buffer[i] = toHexString1(b[i]);
        }
        return buffer;
    }

    public static String toHexString1(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
            return "0" + s;
        } else {
            return s;
        }
    }

    /**
     * byte进制转换    打印工具
     *
     * @param data
     */
    public static void LogPrintOutForByte(String tag, byte[] data) {
        for (byte mByte : data) {
            Log.d(tag + "0", Byte.toString(mByte));                     //原始byte
            Log.d(tag + "1", ByteUtils.toHexString1(mByte));            //16进制byte
            Log.d(tag + "2", "" + Integer.valueOf(ByteUtils.toHexString1(mByte), 16));    //10进制byte
        }
        Log.d(tag + "0", "------------------------------");
        Log.d(tag + "1", "------------------------------");
        Log.d(tag + "2", "------------------------------");
    }

    /**
     * String转Base64
     *
     * @param inputData
     * @return
     */
    public static byte[] string2Base64(String inputData) {
        if (inputData.equals("") || inputData == null) {
            return null;
        } else {
            return Base64.decode(inputData.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT);
        }
    }

    public static byte[] string2Int16(String[] str) {
        byte[] mByte = new byte[str.length];
        for (int i = 0; i < str.length; i++) {
            mByte[i] = (byte) Integer.parseInt(str[i], 16);
        }
        return mByte;
    }
}
